package org.lingshi.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;


@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private MyAccessDeniedHandler deniedHandler;
    @Autowired
    private MyAuthenticationSucessHandler authcSucessHandler;
    @Autowired
    private UserDetailsService detailsService;
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //1.旅行设置（不用认证）
        http.authorizeRequests()
                .antMatchers(
                        "/login",
                        "/form","/static/**",
                        "/System/User/**",
                        "/Question/**"
                    ).permitAll().anyRequest()
                .authenticated();

        //2.登录设置
        http.formLogin().loginPage("/login")
                .loginProcessingUrl("/form")
                .successHandler(authcSucessHandler)
                .failureUrl("/loginFailed")
                .permitAll();
        //3.退出设置
        http.logout().logoutSuccessUrl("/login")
                .invalidateHttpSession(true);
        //4.跨站安全策略设置
        http.csrf().disable();
        //5.无法访问的消息处理处理器绑定
        http.exceptionHandling().accessDeniedHandler(deniedHandler);
    }
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder builder) throws Exception {
        //1.用户认证服务绑定
        //2.设置密码编码器
        builder.userDetailsService(detailsService).passwordEncoder(new BCryptPasswordEncoder());
    }

}
